package top100.stack;

import javafx.util.Pair;
import java.util.*;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/28 9:27
 * @description:
 */
public class Solution347 {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
//        PriorityQueue<Pair<Integer, Integer>> heap = new PriorityQueue<>(new Comparator<Pair<Integer, Integer>>() {
//            @Override
//            public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
//                return o1.getValue() - o2.getValue();
//            }
//        });

//        PriorityQueue<Pair<Integer, Integer>> heap = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());

        PriorityQueue<Pair<Integer, Integer>> heap = new PriorityQueue<>(Comparator.comparingInt(Pair::getValue));
        for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
            if (heap.size() < k) {
                heap.add(new Pair<>(pair.getKey(), pair.getValue()));
            } else {
                heap.add(new Pair<>(pair.getKey(), pair.getValue()));
                heap.poll();
            }
        }
        int[] res = new int[k];
        int i = 0;
        while (!heap.isEmpty()) {
            res[i++] = heap.poll().getKey();
        }
        return res;
    }

    public static void main(String[] args) {
        Solution347 solution = new Solution347();
        System.out.println(Arrays.toString(solution.topKFrequent(new int[]{1, 1, 2, 2, 3}, 2)));
        System.out.println(Arrays.toString(solution.topKFrequent(new int[]{1}, 1)));
        System.out.println(Arrays.toString(solution.topKFrequent(new int[]{1, 2, 1, 2, 1, 2, 3, 1, 3, 2}, 2)));
    }
}
